package com.ruoyi.web.controller.module.thirdpard;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.OrderGift;
import com.ruoyi.order.domain.OrderGoods;
import com.ruoyi.order.domain.OrderWallet;
import com.ruoyi.order.service.IOrderGiftService;
import com.ruoyi.order.service.IOrderGoodsService;
import com.ruoyi.order.service.IOrderWalletService;
import com.ruoyi.thirdpart.service.IBizWechatPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;


/**
 * 支付
 * 
 * @author ganluhua
 */
@RestController
@RequestMapping("/thirdpart/pay")
public class PayController extends BaseController
{

    @Autowired
    private IBizWechatPayService wechatPayService;

    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private IOrderGiftService orderGiftService;

    @Autowired
    private IOrderWalletService orderWalletService;


    /**
     * 微信公众号支付回调
     */
    @RequestMapping("/wxPayCallback/{payType}/{financeType}/{shopId}")
    @Log(title = "微信公众号支付回调", businessType = BusinessType.INSERT)
    public void wxPayNotify(@PathVariable("payType") String payType,
                       @PathVariable("financeType") String financeType,
                       @PathVariable("shopId") String shopId,
                       @RequestBody(required = false) String data)
    {
        try {
            WxPayOrderNotifyResult result = wechatPayService.wxPayService(payType, shopId).parseOrderNotifyResult(data);
            System.out.println("========== 微信公众号支付回调 ==========");
            // 支付返回信息
            if ("SUCCESS".equals(result.getReturnCode())) {
                // 可以实现自己的业务逻辑
                if(financeType.equals(UserConstants.FINANCE_ORDER)){
                    // 下单类型
                    OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(result.getOutTradeNo());
                    if(orderGoods.getPayStatus().equals(UserConstants.PAY_STATUS_UNPAID)){
                        orderGoods.setPayStatus(UserConstants.PAY_STATUS_PAID);
                        // 订单完成服务才能结算 这里不能结算
                        orderGoodsService.updateOrderGoods(orderGoods);
                        orderGoodsService.finishPay(orderGoods);
                    }
                }
                if(financeType.equals(UserConstants.FINANCE_GIFT)){
                    // 打赏类型
                    OrderGift orderGift = orderGiftService.selectOrderGiftByOrderNo(result.getOutTradeNo());
                    if(orderGift.getPayStatus().equals(UserConstants.PAY_STATUS_UNPAID)){
                        // 在结算中心会更新订单
                        orderGiftService.settleCenter(orderGift);
                    }
                }
                if(financeType.equals(UserConstants.FINANCE_RECHARGE)){
                    // 充值类型
                    OrderWallet orderWallet = orderWalletService.selectOrderWalletByOrderNo(result.getOutTradeNo());
                    if(orderWallet.getPayStatus().equals(UserConstants.PAY_STATUS_UNPAID)){
                        // 在结算中心会更新订单
                        orderWalletService.settleCenter(orderWallet);
                    }
                }
                // logger.info("来自微信支付的回调:{}", result);
            }
        } catch (WxPayException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 微信退款
     *
     * @param orderNo
     */
    @RequestMapping(method = RequestMethod.POST, value = "wxPayRefund")
    public void wxPayRefund(String orderNo, String financeType) {
        BigDecimal actualAmount = new BigDecimal(0);
        String shopId = "";
        String payType = "";
        // 可以实现自己的业务逻辑
        if(financeType.equals(UserConstants.FINANCE_ORDER)){
            // 下单类型
            OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(orderNo);
            actualAmount = orderGoods.getActualAmount();
            shopId = orderGoods.getShopId();
            payType = orderGoods.getPayType();
        }
        if(financeType.equals(UserConstants.FINANCE_GIFT)){
            // 打赏类型
            OrderGift orderGift = orderGiftService.selectOrderGiftByOrderNo(orderNo);
            actualAmount = orderGift.getActualAmount();
            shopId = orderGift.getShopId();
            payType = orderGift.getPayType();
        }
        if(financeType.equals(UserConstants.FINANCE_RECHARGE)){
            // 充值类型
            OrderWallet orderWallet = orderWalletService.selectOrderWalletByOrderNo(orderNo);
            actualAmount = orderWallet.getActualAmount();
            shopId = orderWallet.getShopId();
            payType = orderWallet.getPayType();
        }
        BigDecimal yibai = new BigDecimal("100");
        float totalFee = actualAmount.multiply(yibai).intValue();
        // totalFee 必须要以分为单位,退款的价格可以这里只做的全部退款
        WxPayRefundResult refund = wechatPayService.wxRefund(orderNo, (int) totalFee, payType, financeType, shopId);
        // 实现自己的逻辑
        logger.info("退款本地回调:{}", refund);
    }

    /**
     * 微信退款回调
     */
    @RequestMapping("/wxRefundCallback/{payType}/{financeType}/{shopId}")
    @Log(title = "微信退款回调", businessType = BusinessType.INSERT)
    public void wxRefundNotify(@PathVariable("payType") String payType,
                       @PathVariable("financeType") String financeType,
                       @PathVariable("shopId") String shopId,
                       @RequestBody(required = false) String data){
        try {
            System.out.println("========== 微信退款回调 ==========");
            WxPayRefundNotifyResult result = wechatPayService.wxPayService(payType, shopId).parseRefundNotifyResult(data);
            WxPayRefundNotifyResult.ReqInfo reqInfo = result.getReqInfo();
            if (reqInfo.getRefundStatus().equals("SUCCESS")) {
                // 退款成功 可以实现自己的业务逻辑
                if(financeType.equals(UserConstants.FINANCE_ORDER)){
                    // 下单类型
                    OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(reqInfo.getOutTradeNo());
                    if(orderGoods.getPayStatus().equals(UserConstants.PAY_STATUS_PAID)){
                        orderGoods.setPayStatus(UserConstants.PAY_STATUS_REFUND_ORIGIN);
                        orderGoods.setStatus(UserConstants.STATUS_CANCEL);
                        orderGoodsService.updateOrderGoods(orderGoods);
                    }
                }
                if(financeType.equals(UserConstants.FINANCE_GIFT)){
                    // 打赏类型
                    OrderGift orderGift = orderGiftService.selectOrderGiftByOrderNo(reqInfo.getOutTradeNo());
                    if(orderGift.getPayStatus().equals(UserConstants.PAY_STATUS_PAID)){
                        orderGift.setPayStatus(UserConstants.PAY_STATUS_REFUND_ORIGIN);
                        orderGiftService.updateOrderGift(orderGift);
                    }
                }
                if(financeType.equals(UserConstants.FINANCE_RECHARGE)){
                    // 充值类型
                    OrderWallet orderWallet = orderWalletService.selectOrderWalletByOrderNo(reqInfo.getOutTradeNo());
                    if(orderWallet.getPayStatus().equals(UserConstants.PAY_STATUS_PAID)){
                        orderWallet.setPayStatus(UserConstants.PAY_STATUS_REFUND_ORIGIN);
                        orderWalletService.updateOrderWallet(orderWallet);
                    }
                }
            }
        }catch (WxPayException e) {
            logger.error(e.getMessage());
        }
    }
}

